package com.netease.financial;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;

import com.netease.financial.base.customerservice.CustomerServiceHelper;
import com.netease.financial.base.lockpattern.LockPatternHelper;
import com.netease.financial.base.lockpattern.LockPatternPreferencesHelper;
import com.netease.financial.base.push.PushHelper;
import com.netease.financial.common.config.NfsConfig;
import com.netease.financial.common.util.NfsLog;
import com.netease.financial.common.util.preferences.PreferencesHelper;
import com.netease.financial.internal.di.components.ApplicationComponent;
import com.netease.financial.internal.di.components.DaggerApplicationComponent;
import com.netease.financial.internal.di.modules.ApplicationModule;
import com.netease.financial.navigation.Navigator;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.tendcloud.tenddata.TCAgent;

import javax.inject.Inject;

/**
 * Created by wyf on 6/19/15.
 */
public class NfsApplication extends Application {

    private static final String TAG = NfsApplication.class.getSimpleName();

    private Handler mHandler;
    private Activity currentActivity;
    private ApplicationComponent applicationComponent;

    @Inject
    Navigator navigator;

    private static NfsApplication sFinancialApplication;

    @Override
    public void onCreate() {
        super.onCreate();
        sFinancialApplication = this;
        mHandler = new Handler(getMainLooper());
        initConfig(); // must be init first
        initPreferences();
        initPush(); // 推送
        initTalkingData(); //Talking data
        initImageLoader(getApplicationContext()); //图片加载
        initCustomerService(); // 客服
        registerActivityLifecycleCallbacks();
        initLockPattern();
        initializeInjector();
    }

    public Navigator getNavigator() {
        return navigator;
    }

    private void initializeInjector() {
        this.applicationComponent = DaggerApplicationComponent.builder()
                .applicationModule(new ApplicationModule(this))
                .build();
        this.applicationComponent.inject(this);
    }

    public ApplicationComponent getApplicationComponent() {
        return this.applicationComponent;
    }

    private void initLockPattern() {
        LockPatternHelper.init(this);
    }

    private void initConfig() {
        NfsConfig.init(getApplicationContext());
    }

    private void initPreferences() {
        PreferencesHelper.init(getApplicationContext());
    }

    private void initCustomerService() {
        CustomerServiceHelper.init(this);
    }

    private void registerActivityLifecycleCallbacks() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

            }

            @Override
            public void onActivityStarted(Activity activity) {
                currentActivity = activity;
            }

            @Override
            public void onActivityResumed(Activity activity) {
                mHandler.removeCallbacks(mAppEnterBackgroundRunnable);
                boolean isAppFromBackground = LockPatternPreferencesHelper.isAppFromBackground();
                if (isAppFromBackground) {
                    LockPatternPreferencesHelper.setAppInBackground(false);
                    appWillEnterForeground(activity);
                }
                LockPatternHelper.onActivityResumed(activity);
                currentActivity = activity;
                TCAgent.onResume(activity);
            }

            @Override
            public void onActivityPaused(Activity activity) {
                TCAgent.onPause(activity);
                mHandler.postDelayed(mAppEnterBackgroundRunnable, 100L);
            }

            @Override
            public void onActivityStopped(Activity activity) {
                currentActivity = activity;
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                currentActivity = activity;
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                currentActivity = activity;
            }
        });
    }

    public static NfsApplication getApplication() {
        return sFinancialApplication;
    }

    private void initTalkingData() {
        TCAgent.LOG_ON = NfsLog.DEBUG_MODE;
        TCAgent.init(this); //Init TalkingData
        TCAgent.setReportUncaughtExceptions(true);
    }

    private void initPush() {
        PushHelper.setDebugMode(NfsLog.DEBUG_MODE);    // 设置开启日志,发布时请关闭日志
        PushHelper.init(this);            // 初始化 JPush
    }

    private void initImageLoader(Context context) {
        // This configuration tuning is custom. You can tune every option, you may tune some of them,
        // or you can tryCreate default configuration by
        //  ImageLoaderConfiguration.createDefault(this);
        // method.
        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
        config.threadPriority(Thread.NORM_PRIORITY - 2);
        config.denyCacheImageMultipleSizesInMemory();
        config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
        config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
        config.tasksProcessingOrder(QueueProcessingType.LIFO);
        config.writeDebugLogs(); // Remove for release app

        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config.build());
    }

    private Runnable mAppEnterBackgroundRunnable = new Runnable() {
        @Override
        public void run() {
            LockPatternPreferencesHelper.setAppInBackground(true);
            appDidEnterBackground(currentActivity);
        }
    };

    private void appWillEnterForeground(Activity activity) {
        NfsLog.d(TAG, "appWillEnterForeground");
        LockPatternHelper.appWillEnterForeground(activity);
    }

    private void appDidEnterBackground(Activity activity) {
        NfsLog.d(TAG, "appDidEnterBackground");
        LockPatternHelper.appDidEnterBackground(activity);
    }
}
